import lwpgt

class Tile:
    """tile class for each tile on the map"""
    def __init__(self, image, tilesize=(32, 32), static=False):
        """init new tile"""
        self.image=image
        self.size=image.get_size()[:]
        self.width=tilesize[0]
        self.height=tilesize[1]
        
        #animations data
        self.static=static
        self.CountFrames()
        self.current_frame=0
        self.animation_delay=0.500
        self.animation_timer=lwpgt.tools.Timer()
        self.framelist=[]
        
        #update framelist
        self.SetAnimationFrames()
        
    def GetImage(self):
        """return tile image"""
        if len(self.framelist)>0:
            return self.image.subsurface((self.width*self.framelist[self.current_frame], 0, self.width, self.image.get_size()[1]))
        else:
            return self.image.subsurface((self.width, 0, self.width, self.image.get_size()[1]))
    
    def SetImage(self, img):
        """set image for tile"""
        self.image=img
        self.size=img.get_size()[:]
    
    def SetAnimationDelay(self, interval):
        """set animation delay for this tile"""
        self.animation_delay=interval
    
    def SetAnimationFrames(self, framelist=None):
        """set animation frames
        framelist is a list of frames to draw eg. [0,1,2]"""
        if framelist!=None:
            self.framelist=framelist[:]
        else:
            self.framelist=range(0, self.number_of_frames)
    
    def CountFrames(self):
        """Count number of frames on the image"""
        if not self.static:
            self.number_of_frames=self.image.get_size()[0]/self.width
        else:
            self.number_of_frames=1
    
    def SetStatic(self, static=True):
        """set static flag for this tile"""
        self.static=static
    
    def Draw(self, surface, position):
        """redraw tile on the given surface at given position"""
        #animation progress
        if self.animation_timer.Tick(self.animation_delay):self.current_frame+=1
        if self.current_frame>=len(self.framelist):self.current_frame=0
        
        #if image set then draw it
        if self.image!=None:
            surface.blit(self.GetImage(), (position[0], position[1]))
